<template>
  <div class="register-container">
    <div class="card shadow-sm">
      <div class="card-body">
        <div class="text-center mb-4">
          <i class="bi bi-person-plus fs-1 text-success"></i>
          <h2 class="mt-2">用户注册</h2>
          <p class="text-muted">创建您的商城账户</p>
        </div>

        <form @submit.prevent="handleRegister">
          <div class="mb-3">
            <label for="username" class="form-label">用户名</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-person"></i></span>
              <input
                  type="text"
                  class="form-control"
                  id="username"
                  v-model="form.username"
                  placeholder="请输入用户名"
                  required
                  :class="{ 'is-invalid': errors.username }"
              >
            </div>
            <div v-if="errors.username" class="invalid-feedback d-block">
              {{ errors.username }}
            </div>
          </div>

          <div class="mb-3">
            <label for="email" class="form-label">电子邮箱</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-envelope"></i></span>
              <input
                  type="email"
                  class="form-control"
                  id="email"
                  v-model="form.email"
                  placeholder="请输入电子邮箱"
                  required
                  :class="{ 'is-invalid': errors.email }"
              >
            </div>
            <div v-if="errors.email" class="invalid-feedback d-block">
              {{ errors.email }}
            </div>
          </div>

          <div class="mb-3">
            <label for="password" class="form-label">密码</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-lock"></i></span>
              <input
                  type="password"
                  class="form-control"
                  id="password"
                  v-model="form.password"
                  placeholder="请输入密码（至少6位）"
                  required
                  :class="{ 'is-invalid': errors.password }"
                  @input="checkPasswordStrength"
              >
            </div>
            <div v-if="errors.password" class="invalid-feedback d-block">
              {{ errors.password }}
            </div>
            <div class="mt-2">
              <div class="progress" style="height: 8px;">
                <div
                    class="progress-bar"
                    :class="passwordStrengthClass"
                    role="progressbar"
                    :style="{ width: passwordStrength + '%' }"
                ></div>
              </div>
              <div class="text-muted small mt-1">
                密码强度: {{ passwordStrengthText }}
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label for="confirmPassword" class="form-label">确认密码</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-lock-fill"></i></span>
              <input
                  type="password"
                  class="form-control"
                  id="confirmPassword"
                  v-model="form.confirmPassword"
                  placeholder="请再次输入密码"
                  required
                  :class="{ 'is-invalid': errors.confirmPassword }"
              >
            </div>
            <div v-if="errors.confirmPassword" class="invalid-feedback d-block">
              {{ errors.confirmPassword }}
            </div>
          </div>

          <div class="mb-3">
            <label for="role" class="form-label">用户角色</label>
            <div class="input-group">
              <span class="input-group-text"><i class="bi bi-person-badge"></i></span>
              <select
                  class="form-select"
                  id="role"
                  v-model="form.role"
                  required
              >
                <option value="BUYER">买家</option>
                <option value="SELLER">卖家</option>
              </select>
            </div>
            <div class="form-text">选择买家可购买商品，选择卖家可销售商品</div>
          </div>

          <div class="mb-3 form-check">
            <input
                type="checkbox"
                class="form-check-input"
                id="terms"
                v-model="form.agreeTerms"
                required
            >
            <label class="form-check-label" for="terms">
              我同意 <router-link to="/terms">服务条款</router-link> 和 <router-link to="/privacy">隐私政策</router-link>
            </label>
          </div>

          <div v-if="errorMessage" class="alert alert-danger">
            <i class="bi bi-exclamation-circle me-2"></i>{{ errorMessage }}
          </div>

          <div class="d-grid mb-3">
            <button
                type="submit"
                class="btn btn-success btn-lg"
                :disabled="isLoading"
            >
              <template v-if="isLoading">
                <span class="spinner-border spinner-border-sm me-2" role="status"></span>
                注册中...
              </template>
              <template v-else>
                <i class="bi bi-person-plus me-2"></i>立即注册
              </template>
            </button>
          </div>

          <div class="text-center">
            <p class="mb-0">
              已有账号? <router-link to="/login">立即登录</router-link>
            </p>
          </div>
        </form>
      </div>
    </div>

    <div class="mt-4 text-center">
      <p class="text-muted small">
        注册即表示您同意我们的服务条款和隐私政策。我们不会向第三方共享您的个人信息。
      </p>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { userApi } from '@/api'

export default {
  setup() {
    const router = useRouter()

    const form = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: '',
      role: 'BUYER',
      agreeTerms: false
    })

    const errors = reactive({
      username: '',
      email: '',
      password: '',
      confirmPassword: ''
    })

    const errorMessage = ref('')
    const isLoading = ref(false)

    // 密码强度相关
    const passwordStrength = ref(0)
    const passwordStrengthText = ref('弱')
    const passwordStrengthClass = ref('bg-danger')

    // 密码强度检测
    const checkPasswordStrength = () => {
      const password = form.password
      let strength = 0

      // 长度检查
      if (password.length >= 6) strength += 20
      if (password.length >= 8) strength += 20

      // 字符多样性
      if (/[A-Z]/.test(password)) strength += 20
      if (/[a-z]/.test(password)) strength += 20
      if (/[0-9]/.test(password)) strength += 10
      if (/[^A-Za-z0-9]/.test(password)) strength += 10

      passwordStrength.value = Math.min(strength, 100)

      // 设置文本和颜色
      if (passwordStrength.value < 30) {
        passwordStrengthText.value = '弱'
        passwordStrengthClass.value = 'bg-danger'
      } else if (passwordStrength.value < 70) {
        passwordStrengthText.value = '中等'
        passwordStrengthClass.value = 'bg-warning'
      } else {
        passwordStrengthText.value = '强'
        passwordStrengthClass.value = 'bg-success'
      }
    }

    // 表单验证
    const validateForm = () => {
      let isValid = true

      // 重置错误信息
      Object.keys(errors).forEach(key => errors[key] = '')

      // 用户名验证
      if (form.username.length < 3) {
        errors.username = '用户名至少需要3个字符'
        isValid = false
      }

      // 邮箱验证
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(form.email)) {
        errors.email = '请输入有效的电子邮箱'
        isValid = false
      }

      // 密码验证
      if (form.password.length < 6) {
        errors.password = '密码至少需要6个字符'
        isValid = false
      }

      // 确认密码验证
      if (form.password !== form.confirmPassword) {
        errors.confirmPassword = '两次输入的密码不一致'
        isValid = false
      }

      return isValid
    }

    // 注册处理
    const handleRegister = async () => {
      errorMessage.value = ''

      if (!validateForm()) return
      if (!form.agreeTerms) {
        errorMessage.value = '请阅读并同意服务条款和隐私政策'
        return
      }

      isLoading.value = true

      try {
        // 调整注册数据格式
        const response = await userApi.register({
          username: form.username,
          password: form.password,
          email: form.email,
          role: form.role
        })

        // 注册成功提示
        router.push({
          path: '/login',
          query: {
            registerSuccess: true,
            username: form.username
          }
        })

      } catch (error) {
        console.error('注册失败:', error)

        // 更详细的错误处理
        if (error.response?.status === 409) {
          errorMessage.value = '用户名或邮箱已被注册'
        } else if (error.response?.data?.message) {
          errorMessage.value = error.response.data.message
        } else {
          errorMessage.value = '注册失败，请稍后再试'
        }
      } finally {
        isLoading.value = false
      }
    }

    return {
      form,
      errors,
      errorMessage,
      isLoading,
      passwordStrength,
      passwordStrengthText,
      passwordStrengthClass,
      checkPasswordStrength,
      handleRegister
    }
  }
}
</script>

<style scoped>
.register-container {
  max-width: 500px;
  margin: 60px auto;
  padding: 0 15px;
}

.card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
}

.card-body {
  padding: 30px;
}

.input-group-text {
  background-color: #f8f9fa;
  border-right: 0;
}

.form-control:focus, .form-select:focus {
  box-shadow: none;
  border-color: #86b7fe;
}

.btn-success {
  background-color: #198754;
  border-color: #198754;
  transition: all 0.3s;
}

.btn-success:hover {
  background-color: #157347;
  border-color: #146c43;
  transform: translateY(-2px);
}

.btn-success:disabled {
  background-color: #8fc1a9;
  border-color: #8fc1a9;
}

a {
  color: #198754;
  text-decoration: none;
  transition: color 0.2s;
}

a:hover {
  color: #146c43;
  text-decoration: underline;
}

.progress {
  background-color: #e9ecef;
}

/* 密码强度颜色 */
.bg-danger { background-color: #dc3545; }
.bg-warning { background-color: #ffc107; }
.bg-success { background-color: #198754; }
</style>